package com.taichuan.selfcheck.ui.fragment;


import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.taichuan.keysupport.Key;
import com.taichuan.keysupport.view.KS12ListView;
import com.taichuan.selfcheck.R;
import com.taichuan.selfcheck.config.PropertyDefaultValue;
import com.taichuan.selfcheck.mvp.presenter.EmptyPresenter;
import com.taichuan.selfcheck.mvp.viewinterface.EmptyInterface;
import com.taichuan.selfcheck.ui.dialog.ResultDialog;
import com.taichuan.selfcheck.ui.fragment.base.AppBaseFragment;
import com.taichuan.tcutils.taichuan.SystemUtils;
import com.taichuan.tcutils.taichuan.TcDeviceType;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 蓝牙测试
 */
public class BlueToothTestFragment extends AppBaseFragment<EmptyInterface, EmptyPresenter> implements EmptyInterface {

    @BindView(R.id.cbBle)
    CheckBox mCbBleSwitch;
    @BindView(R.id.bleListView)
    KS12ListView bleListView;
    @BindView(R.id.scanDevice)
    Button scanDevice;//扫描设备
    @BindView(R.id.backDevice)
    Button backDevice;
    @BindView(R.id.tips_textView)
    TextView tipsTv;

    private ArrayAdapter<String> mDevicesAdapter;
    private BluetoothAdapter mBtAdapter;
    private String noDevices = "暂无发现设备";
    ResultDialog resultDialog;
    private final int WHAT_STOP_SCAN_TIMEOUT=1;
    private int scanTimeOut=10;//蓝牙扫描超时10秒

    private Handler mHandler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                case WHAT_STOP_SCAN_TIMEOUT:{//蓝牙扫描超时
                    if(scanTimeOut<=0){
                        scanTimeOut=10;
                        mBtAdapter.cancelDiscovery();
                        hideLoading();
                        if(null != mDevicesAdapter && mDevicesAdapter.getCount() == 0){
                            mDevicesAdapter.add(noDevices);
                        }
                    }else{
                        scanTimeOut--;
                        mHandler.sendEmptyMessageDelayed(WHAT_STOP_SCAN_TIMEOUT,1000);
                    }
                    break;
                }
            }
            return false;
        }
    });

    @Override
    protected boolean isAllowAutoFinishFragment() {
        return false;
    }

    @Override
    public void doOnAutoFinishFragment() {
        resultDialog.show();
    }

    @Override
    protected void getBundleValues(Bundle bundle) {

    }

    @Override
    protected int setContentViewId() {
        return R.layout.fragment_ble;
    }

    @Override
    protected void initView(View view, Bundle bundle) {
        if (SystemUtils.getTcDeviceType() == TcDeviceType.A33_VERTICAL_KEY ||
                SystemUtils.getTcDeviceType() == TcDeviceType.A33_LANDSCAPE_KEY ||
                SystemUtils.getTcDeviceType() == TcDeviceType.A64_LANDSCAPE_KEY ||
                SystemUtils.getTcDeviceType() == TcDeviceType.A64_VERTICAL_KEY ||
                SystemUtils.getTcDeviceType() == TcDeviceType.L10_Pro ||
                SystemUtils.getTcDeviceType() == TcDeviceType.RK3399_LANDSCAPE_KEY) {
            backDevice.setVisibility(View.VISIBLE);
        }
        tipsTv.setText(Html.fromHtml(getString(R.string.ctrl_tips_bluetooth_test)));

        resultDialog = new ResultDialog(PropertyDefaultValue.FUNCTION_TEST_16, getResources().getString(R.string.blue_tooth_test), mActivity);       //设置弹窗发送的事件——蓝牙测试
        // 获取本地蓝牙适配器
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        // 判断蓝牙是否可用
        if (mBtAdapter == null) {
            showMsg("蓝牙是不可用的");
            operateFragmentManagerBack();
            return;
        }
        if (mBtAdapter.isEnabled()) {
            mCbBleSwitch.setChecked(true);
        }
        mCbBleSwitch.setOnCheckedChangeListener(blueToothListener);
        // 搜索到的可用设备
        mDevicesAdapter = new ArrayAdapter<String>(getActivity(),
                R.layout.item_device_name);
//        mDevicesAdapter.add(noDevices);
        bleListView.setAdapter(mDevicesAdapter);

        //注册蓝牙广播
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        mActivity.registerReceiver(mReceiver, filter);

        if (SystemUtils.getTcDeviceType() == TcDeviceType.A33_VERTICAL_KEY ||
                SystemUtils.getTcDeviceType() == TcDeviceType.A33_LANDSCAPE_KEY ||
                SystemUtils.getTcDeviceType() == TcDeviceType.A64_LANDSCAPE_KEY ||
                SystemUtils.getTcDeviceType() == TcDeviceType.A64_VERTICAL_KEY ||
                SystemUtils.getTcDeviceType() == TcDeviceType.L10_Pro ||
                SystemUtils.getTcDeviceType() == TcDeviceType.RK3399_LANDSCAPE_KEY) {
            mViewFocus.removeAll();
            mViewFocus.add(mCbBleSwitch);
            mViewFocus.add(scanDevice);
            mViewFocus.add(backDevice);
            mViewFocus.add(bleListView);
            mViewFocus.requestFocus(bleListView);
        }

    }


    private CompoundButton.OnCheckedChangeListener blueToothListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
            if (checked) {
                //如果蓝牙已经是打开状态，则直接提示结束
                if (mBtAdapter.getState() == BluetoothAdapter.STATE_ON) {
                    showMsg(R.string.open_bluetooth_success);
                    return;
                }
                //打开蓝牙
                if (mBtAdapter.enable()) {
                    showMsg(R.string.open_bluetooth_success);
                } else {
                    showMsg(R.string.open_bluetooth_failure);
                    mCbBleSwitch.setChecked(false);
                }
            } else {
                //如果蓝牙已经是关闭状态，则直接提示结束
                if (mBtAdapter.getState() == BluetoothAdapter.STATE_OFF) {
                    showMsg(R.string.close_bluetooth_success);
                    return;
                }
                //关闭蓝牙
                if (mBtAdapter.disable()) {
                    showMsg(R.string.close_bluetooth_success);
                } else {
                    showMsg(R.string.close_bluetooth_failure);
                    mCbBleSwitch.setChecked(true);
                }
                mDevicesAdapter.clear();
            }
        }
    };

    @OnClick({R.id.scanDevice, R.id.backDevice})
    @Override
    protected void onXmlClick(View v) {
        super.onXmlClick(v);
        switch (v.getId()) {
            case R.id.scanDevice: {//扫描设备
                if (mBtAdapter.isEnabled()) {
                    mDevicesAdapter.clear();
                    showLoading();
                    discoverDevice();
                } else {
                    showMsg("请先开启蓝牙");
                }
                break;
            }
            case R.id.backDevice: {
                operateFragmentManagerBack();
                break;
            }
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (resultDialog.isShowing()) {
            resultDialog.dispatchKeyEvent(event);
        }
        if (event.getKeyCode() == Key.Convert.KEYCODE_XING) {
            if (mViewFocus.onFocused(mCbBleSwitch)
                    || mViewFocus.onFocused(backDevice)
                    || mViewFocus.onFocused(bleListView)
                    || mViewFocus.onFocused(scanDevice)) {
                mViewFocus.nextFocus();
                return true;
            }
        } else if (event.getKeyCode() == Key.Convert.KEYCODE_JING) {
            mViewFocus.handleClick();
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * 监听搜索到的设备
     */
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {

                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    if (!TextUtils.isEmpty(device.getName())) {
                        mDevicesAdapter.add(device.getName() + "\n"
                                + device.getAddress());
                    }
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
                    .equals(action)) {
                hideLoading();
                if (mDevicesAdapter.getCount() == 0) {
                    mDevicesAdapter.add(noDevices);
                }
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mBtAdapter != null) {
            mBtAdapter.cancelDiscovery();
        }
        hideLoading();
        mActivity.unregisterReceiver(mReceiver);
    }

    /**
     * 扫描本地可用的设备
     */
    private void discoverDevice() {
        //如果正在扫描，先停止扫描，再重新扫描
        if (mBtAdapter.isDiscovering()) {
            mBtAdapter.cancelDiscovery();
        }
        mBtAdapter.startDiscovery();
        mHandler.sendEmptyMessageDelayed(WHAT_STOP_SCAN_TIMEOUT,1000);
    }

    @Override
    protected EmptyPresenter createPresenter() {
        return new EmptyPresenter();
    }

    @Override
    public void showLoading() {
        mActivity.showStaticDialog("扫描中，请稍后...");
    }

    @Override
    public void hideLoading() {
        mActivity.hideLoading();
    }

}
